<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">个人主页</block>
		</cu-custom>
		<view class="uni-column padding-sm" v-if="detail!=null&&fmSummary!=null">
			<view class="uni-row padding-left-lg">
				<view class="flex uni-column justify-center">
					<view class="text-sm text-blue text-bold text-center">OKEX</view>
					<view class="cu-avatar lg round" :style="[{ backgroundImage:'url(' + fmSummary.photo + ')' }]">
						<view class="cu-tag badge cuIcon-vip bg-yellow"></view>
					</view>
				</view>
				<view class="flex-twice uni-column margin-left-lg">
					<view class="flex-sub text-sm  text-gray">该用户已将多空倍数隐藏</view>
					<view class="flex-treble text-xxl">{{fmSummary.nickname}}</view>
					<view class="flex-sub text-sm  text-gray">{{fmSummary.selfDesc}}</view>
				</view>
			</view>
			<view style="max-height: 65vh;overflow-y: auto;">
				<view class="flex uni-column radius bg-white padding-sm margin-top" v-if="fmSummary!=null">
					<view class="justify-start text-lg solid-bottom">帐户概览</view>
					<view class="uni-column">
						<view class="grid col-2 solid-bottom">
							<view class="text-df">帐户资金</view>
							<view class="text-df">总收益率</view>
							<view class="text-df text-bold">{{fmSummary.currentBalance}}$</view>
							<view class="text-df text-bold" :class="fmSummary.earnRate>0?'item-value-total account-up':'item-value-total account-down'">{{fmSummary.earnRate}}%</view>
						</view>
						<view class="grid col-3">
							<view class="text-sm text-grey">总收益额</view>
							<view class="text-sm text-grey">交易胜率</view>
							<view class="text-sm text-grey">交易时间</view>
							<view class="text-sm text-bold" :class="fmSummary.earn>0?'text-green':'text-red'">{{fmSummary.earn}}$</view>
							<view class="text-sm text-bold" >{{fmSummary.winRate*100}}%</view>
							<view class="text-sm text-bold" >{{fmSummary.dealDayNum}}天</view>

							<view class="text-sm text-grey">周收益</view>
							<view class="text-sm text-grey">周收益率</view>
							<view class="text-sm text-grey">交易频次</view>
							<view class="text-sm text-bold" :class="fmSummary.weekEarn>0?'text-green':'text-red'">{{fmSummary.weekEarn}}$</view>
							<view class="text-sm text-bold" :class="fmSummary.weekEarnRate>0?'text-green':'text-red'">{{fmSummary.weekEarnRate}}%</view>
							<view class="text-sm text-bold" >{{fmSummary.weekOprRate}}/天</view>
						</view>
					</view>
				</view>

				<view class="flex uni-column radius bg-white padding-sm margin-top">
					<view class="justify-start text-lg solid-bottom">仓位一览</view>
					<view v-if="detail.isPositionLocked" class="text-center padding">锁定可见范围</view>
					<view class="grid col-3" v-else-if="fmatPosition!=null&&fmatPosition.length!=0">
						<view v-for="(item,index) in fmatPosition" :key='index'>
							<view class="grid col-2 radius padding-sm" style="border: #D9D9D9 1px solid; margin: 5rpx;">
								<view class="text-sm ">{{item.instrument[0]}}</view>
								<view class="text-sm text-bold text-right">{{item.alias}}{{item.direction=='long'?'多':'空'}}</view>
								<view class="text-sm ">杠杆</view>
								<view class="text-sm text-bold text-right">{{item.leverage}}倍</view>
								<view class="text-sm ">张数</view>
								<view class="text-sm text-bold text-right"> {{item.qty}}张</view>
								<view class="text-sm ">盈亏</view>
								<view class="text-sm text-bold text-right" :class="item.rate>0?'text-green':'text-red'"> {{item.rate}}%</view>
							</view>
						</view>
					</view>
					<view v-else class="text-center padding">当前无持仓</view>
				</view>
				<view class="flex uni-column radius bg-white padding-sm margin-top">
					<view class="justify-start text-lg solid-bottom">收益率</view>
					<view>
						<view v-if="detail.isAccountLocked" class="text-center padding">锁定可见范围</view>
						<view v-else-if="detail.history!=null&&detail.history.length!=0" class="qiun-charts">
							<canvas canvas-id="canvasArea" id="canvasArea" class="charts" @touchstart="touchArea"></canvas>
						</view>
						<view v-else class="text-center padding">暂无收益数据</view>
					</view>
				</view>
				<view class="flex uni-column radius bg-white padding-sm margin-top">
					<view class="justify-start text-lg solid-bottom">最新操作</view>
					<view>
						<view v-if="detail.isActionLocked" class="text-center padding">锁定可见范围</view>
						<view class="cu-timeline" v-else-if="fmtActions!=null&&fmtActions.length!=0">
							<view class="cu-item cur cuIcon-noticefill" v-for="(item,index) of fmtActions" :key="index">
								<view class="uni-column content text-sm" :class="item.state=='over_deal'?'bg-grey':item.direction=='BUY_LONG'?'bg-green':'bg-red'">
									<view>{{item.time_str}}</view>
									<view>{{item.category=='future_single_martin'?'铁三角':'未知'}} {{item.direction=='BUY_LONG'?'开多':'开空'}}</view>
									<view>{{item.instrumentDesc}}&nbsp;&nbsp;共{{item.floorMount}}张</view>
									<view>{{item.state=='over_deal'?'交易完成':'未完成'}}</view>
									<view class="flex">
										<view class="flex-sub"><button class="cu-btn  sm" @tap="showParam(index)">详 情</button></view>
										<view class="flex-sub"><button class="cu-btn  sm" @tap="showPreview(item)">跟 单</button></view>
									</view>
									<view v-if="item.show" class="grid margin-bottom  col-1 bg-gray margin-tb-sm">
										<view class="flex" v-for="(param,index2) in item.params" :key="index2">
											<view class="flex-sub text-xs padding-left-sm" v-if="param.value!='null'">{{param.description}}</view>
											<view class="flex-sub text-xs" v-if="param.value!='null'">{{param.value}}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="text-center padding">最近无操作</view>
					</view>
				</view>
			</view>
		</view>
		<view class="solid-top flex justify-center padding-top-lg"  v-if="detail!=null&&detail.summary.isMyOrdered">
			<button class="cu-btn bg-grey lg ">仅支持{{detail.summary.joinType=='bkb'?'BKB':detail.summary.joinType=='serial'?'序列号':detail.summary.joinType=='everyone'?'免费':'其它'}}订阅</button>
			<button class="cu-btn bg-gradual-blue  round lg margin-left-lg" @click="unSub">取消订阅</button>
		</view>
		<view class="solid-top flex justify-center padding-top-lg"  v-else-if="detail!=null&&detail.summary.joinType=='bkb'">
			<view class="solid bg-white">
				<wm-numberBox destination="body-btn" model="1" :min="box.min" :max="box.max" :height="box.height" :value="monthNum"
				 @change="changeMonth"></wm-numberBox>
			</view>
			<view>
				<button class="cu-btn bg-gradual-blue  round lg margin-left-lg" @click="toConfirm">{{detail.summary.bkbCast*monthNum}}BKB/{{monthNum < 2?'':monthNum}}月</button>
			</view>
		</view>
		<view class="solid-top flex justify-center padding-top-lg "  v-else-if="detail!=null&&detail.summary.joinType=='serial'">
			<view class="cu-form-group">
				<input placeholder="渠道序列号" v-model="sn" name="input" style="width: 200upx;"></input>
			</view>
			<view>
				<button class="cu-btn bg-gradual-blue  round lg margin-left-lg" @click="toConfirm">序列号订阅</button>
			</view>
		</view>
		<view class="solid-top flex justify-center padding-top-lg"  v-else-if="detail!=null&&detail.summary.joinType=='everyone'">
			<button class="cu-btn bg-gradual-blue  round lg margin-left-lg" @click="toConfirm">免费订阅</button>
		</view>
	</view>
</template>

<script>
	import account from './account.vue'
	import uCharts from '@/js_sdk/u-charts/u-charts/u-charts.js';
	import wmNumberBox from "@/components/wm-numberBox/wm-number-box.vue"
	var _self;
	var canvaArea = null;

	export default {
		components: {
			account,
			wmNumberBox
		},
		computed: {
			fmSummary: function() {
				if (this.detail != null && this.detail.summary != null) {
					let fmtSummary = this.detail.summary
					fmtSummary.earn = Number(fmtSummary.currentBalance-fmtSummary.initBalance).toFixed(2)
					fmtSummary.weekEarn = Number(fmtSummary.currentBalance-fmtSummary.weekBeforeBalance).toFixed(2)
					fmtSummary.earnRate = Number(fmtSummary.earn * 100 / fmtSummary.initBalance).toFixed(2)
					fmtSummary.weekEarnRate = Number(fmtSummary.weekEarn * 100 / fmtSummary.weekBeforeBalance).toFixed(2)
					return fmtSummary
				}
				return null
			},
			fmtActions: function() {
				let actions = null
				if (this.detail != null && this.detail.actions != null) {
					actions = this.detail.actions
					for (let item of actions) {
						item.time_str = _self.t2d(item.time)
						let contract = _self.getContractMap().get(item.instrumentId)
						contract.alias == 'quarter' ? '季度' : ''
						let aliasStr = ''
						switch (contract.alias) {
							case 'quarter':
								aliasStr = '季度'
								break;
							case 'this_week':
								aliasStr = '本周'
								break;
							case 'next_week':
								aliasStr = '次周'
								break;
							case 'bi_quarter':
								aliasStr = '次季'
								break;
						}
						// console.log(contract)
						item.instrumentDesc = item.instrumentId.split("-", 2).join('') + (aliasStr)
					}
				}
				return actions.reverse()
			},
			fmatPosition: function() {
				let position = []
				if (this.detail != null && this.detail.position != null) {
					let tempList = this.detail.position;
					for (let item of tempList) {
						console.log(item.instrumentId)
						let contract = _self.getContractMap().get(item.instrumentId)
						console.log(contract)
						let instrument = item.instrumentId.split("-", 2)
						let aliasStr = ''
						switch (contract.alias) {
							case 'quarter':
								aliasStr = '季度'
								break;
							case 'this_week':
								aliasStr = '本周'
								break;
							case 'next_week':
								aliasStr = '次周'
								break;
							case 'bi_quarter':
								aliasStr = '次季'
								break;
						}
						if (item.longQty > 0) {
							position.push({
								'direction': 'long',
								'qty': item.longQty,
								'avg': item.longAvgCost,
								'leverage': item.longLeverage,
								'alias': aliasStr,
								'instrument': instrument,
								'rate': Number(item.longPnlRatio * 100).toFixed(2)
							})

						}
						if (item.shortQty > 0) {
							position.push({
								'direction': 'short',
								'qty': item.shortQty,
								'avg': item.shortAvgCost,
								'leverage': item.shortLeverage,
								'alias': aliasStr,
								'instrument': instrument,
								'rate': Number(item.shortPnlRatio * 100).toFixed(2)
							})
						}
					}
				}
				console.log('position')
				console.log(position)
				return position
			}
		},

		data() {
			return {
				monthNum: 1,
				detail: null,
				sn: '',
				box: {
					min: 1,
					max: 12,
					height: 40
				},
				Area: {
					categories: [],
					series: []
				},
				cWidth: '',
				cHeight: '',
				pixelRatio: 1,
				subInfo: {},
				accountId:null
			}
		},

		onLoad(e) {
			_self = this
			console.log(e.id)
			this.cWidth = uni.upx2px(750);
			this.cHeight = uni.upx2px(500);
			_self.accountId=e.id
			_self.loadDetail()
		},
		methods: {
			changeMonth(e) {
				console.log('change month num')
				console.log(e)
				_self.monthNum = e.value
			},
			showParam(index) {
				console.log('show param')
				console.log(this.detail.actions)
				let item = this.detail.actions[index]
				if (item.show) {
					this.$set(this.detail.actions[index], 'show', false)
				} else {
					this.$set(this.detail.actions[index], 'show', true)
				}
			},
			showPreview(item) {
				if (item.category == 'future_single_martin') {
					let martinPara = {
						mount: '',
						direction: '',
						high: '',
						instrumentId: '',
						low: '',
						leverage: ''
					}
					for (let param of item.params) {
						if (param.name == 'mount') {
							martinPara.mount = param.value
						} else if (param.name == 'direction') {
							martinPara.direction = param.value
						} else if (param.name == 'high') {
							martinPara.high = param.value
						} else if (param.name == 'instrumentId') {
							martinPara.instrumentId = param.value
						} else if (param.name == 'low') {
							martinPara.low = param.value
						} else if (param.name == 'leverage') {
							martinPara.leverage = param.value
						}
					}
					console.log('follow order param is ')
					console.log(martinPara)

					if (this.assertNotEmpty(martinPara.instrumentId, "合约标识为空") &&
						this.assertBigThanZero(martinPara.low, "价格设置不合理") &&
						this.assertBigThanZero(martinPara.high, "价格设置不合理") &&
						this.assertNotEmpty(martinPara.direction, "方向不明确") &&
						this.assertTrue(Number(martinPara.low) < Number(martinPara.high), "高价低于低价") &&
						this.assertBigThanZero(martinPara.mount, "合约张数要大于0")) {
						uni.navigateTo({
							url: '/pages/trade/preview?previewType=margin&martinPara=' + JSON.stringify(martinPara)
						})
					}

				}

			},
			unSub() {
				console.log('un sub ' + _self.detail.summary.id)
				uni.showModal({
					content: '确认取消订阅',
					success: function(res) {
						if (res.confirm) {
							uni.request({
								url: _self.api + '/subscribe/unsub/' + _self.detail.summary.id,
								method: 'POST',
								header: {
									"Authorization": "Bearer " + _self.getToken()
								},
								success: res => {
									console.log('unsub resp')
									console.log(res)
									if (_self.ifElseReturn(res)) {
										uni.showToast({
											title: '取消成功'
										})
										_self.loadDetail()
									}
								}
							});
						} else if (res.cancel) {
							uni.navigateBack({
								delta: -1
							})
						}
					}
				});
			},
			toConfirm() {
				// uni.navigateTo({
				// 	url: './gendan_confirm'
				// })
				_self.subInfo.type = _self.detail.summary.joinType
				_self.subInfo.joinId = _self.detail.summary.id
				if (_self.subInfo.type == 'serial') {
					_self.subInfo.sn = _self.sn
				} else if (_self.subInfo.type == 'bkb') {
					_self.subInfo.bkbMonthNum = _self.monthNum
					_self.subInfo.bkbCast = _self.detail.summary.bkbCast * _self.monthNum
				}

				uni.request({
					url: _self.api + '/subscribe/sub',
					method: 'POST',
					header: {
						"Authorization": "Bearer " + this.getToken()
					},
					data: _self.subInfo,
					success: res => {
						console.log('to confirm resp')
						console.log(res)
						if (_self.ifElseReturn(res)) {
							uni.showToast({
								title: '订阅成功'
							})
							_self.loadDetail()
						}
					}

				});

			},			
			loadDetail() {
				uni.showLoading({
					title:'加载中'
				})
				let accountId=_self.accountId
				console.log('loadDetail ' + accountId)
				uni.request({
					url: this.api + '/realdeals/detail?acId=' + accountId,
					method: 'GET',
					header: {
						"Authorization": "Bearer " + this.getToken()
					},
					success: res => {
						console.log('load detail resps')
						console.log(res.data.data)
						_self.detail = res.data.data

						let Area = {
							categories: [],
							series: []
						};
						let seriesData = {
							name: '帐户资产',
							data: [],
							color: '#3658B9',
							format: (val) => {
								return val.toFixed(4) + '$'
							}
						}
						if (_self.detail != null && _self.detail.history != null) {
							for (let item of _self.detail.history) {

								Area.categories.push(item.dayStr.substr(5, 5))
								seriesData.data.push(item.futureBalance)
							}
							Area.series.push(seriesData)
							_self.Area = Area
							_self.showArea("canvasArea", this.Area);
						}

					},
					complete: () => {
						uni.hideLoading()
					}
				});
			},
			showArea(canvasId, chartData) {
				canvaArea = new uCharts({
					$this: _self,
					canvasId: canvasId,
					type: 'area',
					fontSize: 11,
					legend: true,
					dataLabel: false,
					dataPointShape: false, //是否在图表中显示数据点图形标识
					background: '#021C73',
					pixelRatio: _self.pixelRatio, //像素比，默认为1，仅支付宝小程序需要大于1，其他平台必须为1
					categories: chartData.categories,
					series: chartData.series,
					animation: true, //是否动画展示
					xAxis: {
						type: 'grid',
						disableGrid: true,
						labelCount: 5
					},
					yAxis: {
						splitNumber: 6,
						disableGrid: true,
						min: 10,
						max: 70,
					},
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					extra: {
						area: {
							type: 'curve',
							opacity: 1,
							addLine: true,
							width: 1,
							gradient: true
						}
					}
				});

			},
			touchArea(e) {
				canvaArea.showToolTip(e, {
					format: function(item, category) {
						return category + ' ' + item.name + ':' + item.data
					}
				});
			}
		}
	}
</script>

<style>
	.qiun-charts {
		width: 650upx;
		height: 500upx;
		background-color: #FFFFFF;
	}

	.charts {
		width: 650upx;
		height: 500upx;
		background-color: #FFFFFF;
	}
</style>
